%TITLE "32bit DoubleWord to ASCII Decimal String Converter"

	IDEAL
	P386N
	DOSSEG
	MODEL	small

	DATASEG

	CODESEG

	PUBLIC	bintoasc

;-------------------------------------------------------
; BinToDecASCII
;-------------------------------------------------------
; Input:
; 	eax = 32-bit value to convert
; 	cx = minimum number of digits to output
; 	di = address of string to hold result
; 	Note: assmes string is large enough to hold result
; 	Note: creates full result if cx is less than number
; 	      of digits required to specify the result or cx = 0
; 	Note: if cx = 0 and ax = 0 then length of string will be 0
; 	      set cx = 1 if you want string to be '0' if ax = 0
; 	Note: assumes (2 <= bx <= 16)
; Output:
; 	none
; Registers:
; 	none affected
;-------------------------------------------------------
PROC	bintoasc
	pushad

	xor	si, si		; Set digit-count to 0
	mov	ebx, 10		; Set ebx = 10, for decimal conversion
	jcxz	@@20		; If cx = 0, jump to set cs = 1
@@10:
	xor	edx, edx	; Extend eax to 32-bit eax,edx
	div	ebx		; eax <- eax/ebx ; edx <- remainder
	or	dl, '0'		; Convert dl to ASCII numeric
	push	dx		; Save digit on stack
	inc	si		; Count digits on stack
	loop	@@10		; Loop on minimum digit count
@@20:
	inc	cx		; Set cx = 1 in case this is not done
	cmp	eax, 0		; Is eax = 0? (all digits done?)
	jne	@@10		; If not, continue conversion
	mov	cx, si		; Set cx to stack char count
	jcxz	@@40		; Skip next loop if cx = 0
	cld			; Auto-increment di for stosb
@@30:
	pop	ax		; Pop next digit into al
	stosb			; Store digit in string; advance di
	loop	@@30		; Loop for cx amount of digits in stack
@@40:
	mov	[byte di], 0	; Store ASCIIZ null at end of string

	popad
	ret
ENDP	bintoasc

END
